package com.steven.nio;



import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;

public class NIOFileChannel {
    public static void main(String[] args) throws Exception {
//        read();
//        readWrite();
        transfered();
    }
    public static void  write() throws Exception{
        String str ="你好沙雕";
        FileOutputStream fileOutputStream = new FileOutputStream("D:/test.txt");
        FileChannel channel = fileOutputStream.getChannel();
        //创建缓冲区
        final ByteBuffer allocate = ByteBuffer.allocate(1024);
        //缓冲区写数据
        allocate.put(str.getBytes(StandardCharsets.UTF_8));
        //反转
        allocate.flip();
        //缓冲区数据写到channel中
        channel.write(allocate);
        fileOutputStream.close();
    }

    public static void  read() throws Exception{
        String str ="你好沙雕";
        File file = new File("D:/test.txt");
        FileInputStream fileInputStream = new FileInputStream(file);
        final FileChannel channel = fileInputStream.getChannel();
        final ByteBuffer allocate = ByteBuffer.allocate((int) file.length());
        //数据读取到缓冲区
        channel.read(allocate);
        System.out.println(new String(allocate.array(),StandardCharsets.UTF_8));
    }


    /**
     * 数据拷贝 从一个文件拷贝到另外一个文件
     *  一定要标志位清零，不然永远都是0
     * @throws Exception
     */
    public static void readWrite() throws Exception{
        FileInputStream fileInputStream = new FileInputStream("D:/1.txt");
        final FileChannel channel_in = fileInputStream.getChannel();
        final FileOutputStream fileOutputStream = new FileOutputStream("D:/2.txt");
        final FileChannel channel_out = fileOutputStream.getChannel();
        final ByteBuffer allocate = ByteBuffer.allocate(512);
        while (true){
            //清空标志位
            allocate.clear();
            final int read = channel_in.read(allocate);
            if(read ==-1){
                break;
            }
            allocate.flip();
            channel_out.write(allocate);
        }
        fileInputStream.close();
        fileOutputStream.close();
    }
    public static void transfered() throws Exception{
        FileInputStream fileInputStream = new FileInputStream("D:/1.txt");
        FileOutputStream fileOutputStream = new FileOutputStream("D:/2.txt");
        FileChannel channel_src = fileInputStream.getChannel();
        FileChannel channel_de = fileOutputStream.getChannel();
        channel_de.transferFrom(channel_src,0,channel_src.size());
    }
}
